let refreshing = false;
let queue = []; // 请求队列

const axiosInstance = axios.create({
  baseURL: "http://localhost:8082/api",
  timeout: 30000,
});

// 登录
async function userLogin(username, password) {
  return await axiosInstance.post("/user/login", {
    username,
    password,
  });
}

// 获取用户信息
async function userInfo() {
  return await axiosInstance.post("/user/getUserInfo");
}

// 刷新token
async function refreshToken() {
  const res = await axiosInstance.get("/user/refreshToken", {
    params: {
      token: localStorage.getItem("refresh_token"),
    },
  });
  const { accessToken, refreshToken } = res;
  localStorage.setItem("access_token", accessToken);
  localStorage.setItem("refresh_token", refreshToken);
  return res;
}

// 请求拦截器
axiosInstance.interceptors.request.use((config) => {
  const accessToken = localStorage.getItem("access_token");
  if (accessToken) {
    config.headers.authorization = "Bearer " + accessToken;
  }
  return config;
});

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    console.log(response);
    return response.data;
  },
  async (error) => {
    let { status, data, config } = error.response;
    if (refreshing) {
      return new Promise((resolve) => {
        queue.push({
          config,
          resolve,
        });
      });
    }
    if (status === 401 && !config.url.includes("/user/refreshToken")) {
      refreshing = true;
      const res = await refreshToken(); // 刷新Token
      refreshing = false;
      if (res.code === 10000) {
        queue.forEach(({ config, resolve }) => {
          resolve(axiosInstance(config));
        });
        return axiosInstance(config); // 重发请求
      } else {
        alert(data.msg || "登录过期，请重新登录");
        return {};
      }
    } else {
      return error.response;
    }
  }
);
